import { ref } from 'vue'
import { supabase } from '../../lib/supabase'
import type { Comment, CacheItem, UserCacheItem } from './types'
import { useUiStore } from '../../store/useUiStore'

// 评论缓存系统
const commentCache = new Map<string, CacheItem<Comment[]>>()
const CACHE_DURATION = 10 * 60 * 1000 // 10分钟缓存

// 用户信息缓存
const userCache = new Map<string, UserCacheItem>()
const USER_CACHE_DURATION = 30 * 60 * 1000 // 30分钟缓存

export const useCommentLoader = (movieId: number) => {
  const uiStore = useUiStore()
  const comments = ref<Comment[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const hasMore = ref(true)
  const currentPage = ref(0)
  const pageSize = ref(10)

  // 生成缓存键
  const getCacheKey = (movieId: number, page: number = 0) => {
    return `comments_${movieId}_${page}`
  }

  const getUserCacheKey = (userId: string) => {
    return `user_${userId}`
  }

  // 检查缓存是否有效
  const isCacheValid = (cacheKey: string, duration: number) => {
    const cached = commentCache.get(cacheKey)
    if (!cached) return false
    return Date.now() - cached.timestamp < duration
  }

  // 从缓存获取数据
  const getFromCache = (cacheKey: string): { data: Comment[], hasMore: boolean } | null => {
    if (isCacheValid(cacheKey, CACHE_DURATION)) {
      const cached = commentCache.get(cacheKey)!
      return { data: cached.data, hasMore: cached.hasMore || false }
    }
    return null
  }

  // 设置缓存
  const setCache = (cacheKey: string, data: Comment[], hasMore: boolean) => {
    commentCache.set(cacheKey, {
      data,
      timestamp: Date.now(),
      hasMore
    })
  }

  // 批量获取用户信息（带缓存）
  const batchGetUserProfiles = async (userIds: string[]) => {
    const userMap = new Map()
    const uncachedUserIds: string[] = []

    // 检查缓存
    userIds.forEach(userId => {
      const cacheKey = getUserCacheKey(userId)
      const cached = userCache.get(cacheKey)
      if (cached && Date.now() - cached.timestamp < USER_CACHE_DURATION) {
        userMap.set(userId, cached.data)
      } else {
        uncachedUserIds.push(userId)
      }
    })

    // 批量获取未缓存的用户信息
    if (uncachedUserIds.length > 0) {
      try {
        const { data: profilesData, error: profilesError } = await supabase
          .from('user_profiles')
          .select('id, user_id, name, avatar_url, is_ai')
          .in('user_id', uncachedUserIds)
        
        if (!profilesError && profilesData) {
          profilesData.forEach(profile => {
            const cacheKey = getUserCacheKey(profile.user_id)
            userCache.set(cacheKey, {
              data: profile,
              timestamp: Date.now()
            })
            userMap.set(profile.user_id, profile)
          })
        }
      } catch (error) {
        console.error('Error fetching user profiles:', error)
      }
    }

    return userMap
  }

  // 加载评论（兼容模式 - 支持新旧两种方式）
  const loadComments = async (page: number = 0, append: boolean = false) => {
    const cacheKey = getCacheKey(movieId, page)
    
    // 检查缓存
    const cached = getFromCache(cacheKey)
    if (cached && !append) {
      comments.value = cached.data
      hasMore.value = cached.hasMore
      currentPage.value = page
      return
    }

    loading.value = true
    error.value = null
    
    try {
      const offset = page * pageSize.value
      
      // 获取评论数据（仅选择必要字段）
      const { data: commentsData, error: fetchError } = await supabase
        .from('comments')
        .select('id, user_id, content, likes, dislikes, created_at, updated_at')
        .eq('movie_id', movieId)
        .is('parent_id', null) // 只获取顶级评论
        .order('created_at', { ascending: false })
        .range(offset, offset + pageSize.value - 1)

      if (fetchError) {
        throw fetchError
      }

      // 获取所有用户ID/评论ID
      const userIds = [...new Set(commentsData.map(comment => comment.user_id).filter(Boolean))]
      const commentIds = commentsData.map(comment => comment.id)

      // 并行：批量获取用户信息 + 获取回复数量 + 获取当前用户
      const [userMap, replyStatsResult, currentUserResult] = await Promise.all([
        batchGetUserProfiles(userIds),
        // 使用聚合视图减少传输数据量
        supabase
          .from('comment_stats')
          .select('comment_id, reply_count')
          .in('comment_id', commentIds),
        supabase.auth.getUser()
      ])

      // 过滤 AI 评论（基于用户 is_ai）
      const filteredCommentsData = uiStore.filterAiContent
        ? commentsData.filter((comment) => {
            const up = userMap.get(comment.user_id)
            return !up?.is_ai
          })
        : commentsData

      // 创建回复数量映射（来自视图）
      const replyCountMap = new Map<number, number>()
      if (!replyStatsResult.error && replyStatsResult.data) {
        replyStatsResult.data.forEach((row: any) => {
          replyCountMap.set(row.comment_id, Number(row.reply_count) || 0)
        })
      } else if (replyStatsResult.error) {
        console.error('获取回复数量失败:', replyStatsResult.error)
      }

      // 获取当前用户的投票状态（仅针对展示中的评论）
      const { user } = currentUserResult.data
      let userVotes = new Map()
      if (user) {
        const { data: votes, error: votesError } = await supabase
          .from('comment_votes')
          .select('comment_id, vote_type')
          .eq('user_id', user.id)
          .in('comment_id', filteredCommentsData.map(c => c.id))

        if (!votesError && votes) {
          votes.forEach(vote => {
            userVotes.set(vote.comment_id, vote.vote_type)
          })
        }
      }

      // 转换数据格式
      const formattedComments: Comment[] = filteredCommentsData.map((comment) => {
        const userProfile = userMap.get(comment.user_id)
        return {
          id: comment.id,
          userId: comment.user_id,
          user: {
            id: userProfile?.user_id || comment.user_id,
            name: userProfile?.name || '未知用户',
            avatar: userProfile?.avatar_url,
            isAi: userProfile?.is_ai || false
          },
          content: comment.content,
          likes: comment.likes,
          dislikes: comment.dislikes,
          replies: [], // 暂时不加载回复
          createdAt: comment.created_at,
          updatedAt: comment.updated_at,
          replyCount: replyCountMap.get(comment.id) || 0, // 添加回复数量
          userVote: userVotes.get(comment.id) || 0 // 添加用户投票状态
        }
      })

      // 更新状态
      if (append) {
        comments.value.push(...formattedComments)
      } else {
        comments.value = formattedComments
      }

      // 检查是否还有更多数据
      hasMore.value = formattedComments.length === pageSize.value
      currentPage.value = page

      // 设置缓存
      setCache(cacheKey, formattedComments, hasMore.value)

    } catch (err) {
      error.value = err instanceof Error ? err.message : '加载评论失败'
      console.error('加载评论失败:', err)
    } finally {
      loading.value = false
    }
  }

  // 加载更多评论
  const loadMore = async () => {
    if (!hasMore.value || loading.value) return
    await loadComments(currentPage.value + 1, true)
  }

  // 清除评论缓存
  const clearCommentCache = () => {
    commentCache.clear()
  }

  // 清除用户缓存
  const clearUserCache = () => {
    userCache.clear()
  }

  // 获取当前用户
  const getCurrentUser = async () => {
    try {
      const { data: { user }, error } = await supabase.auth.getUser()
      if (error) throw error
      return user
    } catch (err) {
      console.error('获取当前用户失败:', err)
      return null
    }
  }

  return {
    // 状态
    comments,
    loading,
    error,
    hasMore,
    currentPage,
    pageSize,
    
    // 方法
    loadComments,
    loadMore,
    clearCommentCache,
    clearUserCache,
    getCurrentUser,
    
    // 缓存方法
    getCacheKey,
    getUserCacheKey,
    isCacheValid,
    getFromCache,
    setCache,
    batchGetUserProfiles
  }
}
